'use strict';
// 引入阿里SDK
const Core = require('@alicloud/pop-core');
const Service = require('egg').Service;

/**
 * 阿里短信验证码封装类
 */
class AlismsService extends Service {
    /**
     * 发送短信
     * @param { String } phone 用户手机号 
     * @param { String } code 生成的随机验证码
     * @param { String } templateCode 需要加载的短信模板
     * @param { boolean } isNormal 生成的随机验证码
     * @param { String } jsonStr 请求短信模板对应的参数集合，JSON字符串
     */
    async sendSMS(phone, code, templateCode, isNormal = false, jsonStr = '') {
        const client = await this._client();
        const params = await this._params(phone, code, templateCode,isNormal,jsonStr);
        console.log(params)
        const requestOption = await this._requestOption();
        try {
            const ret = await this._send(client, params, requestOption);
            // {"Message":"OK","RequestId":"80A35575-6DD3-4A7D-B4AD-723F918CBBA5","BizId":"627317463804615179^0","Code":"OK"}
            return JSON.parse(ret);
        } catch (err) {
            return {
                Code: 'Error',
                Message: err.message
            }
        }
    }

    /**
     * 实例化客户端
     */
    async _client() {
        return new Core({
            accessKeyId: this.app.config.aliSMS.accessKeyId,
            accessKeySecret: this.app.config.aliSMS.accessKeySecret,
            endpoint: this.app.config.aliSMS.endpoint,
            apiVersion: this.app.config.aliSMS.apiVersion
        });
    }

    /**
     * 实例化参数
     * @param {*} phone 需要发送的手机号码
     * @param {*} code  需要发送的验证码
     * @param {*} templateCode 需要加载的短信模板
     * @param {*} isNormal 生成的随机验证码
     * @param {*} jsonStr  请求短信模板对应的参数集合，JSON字符串
     */
    async _params(phone, code, templateCode, isNormal, jsonStr) {

        return {
            "RegionId": this.app.config.aliSMS.regionId,
            "PhoneNumbers": `${phone}`,
            "SignName": this.app.config.aliSMS.signName,
            "TemplateCode": templateCode,
            "TemplateParam": isNormal ? jsonStr : `{\"code\":${code}}`
        }
    }

    /**
     * 请求参数类型
     */
    async _requestOption() {
        return {
            method: 'POST'
        }
    }

    /**
     * 发送请求
     * @param {*} client  实例化对象
     * @param {*} params 请求参数
     * @param {*} requestOption 请求类型
     */
    async _send(client, params, requestOption) {
        return new Promise((resolve, reject) => {
            client.request('SendSms', params, requestOption).then((result) => {
                resolve(JSON.stringify(result))
            }, (ex) => {
                reject(ex)
            })
        })
    }
}

module.exports = AlismsService;
